﻿using System;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using EasyWeixin.CommonAPIs;
using EasyWeixin.Entities.JsonResult;

using RaceList.activity.util;

namespace RaceList.activity.help
{
    public class WeixinAuthModule : IHttpModule, IRequiresSessionState
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += context_PreRequestHandlerExecute;
        }

        private void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            AuthWeixin(sender);
        }

        private void InitTest()
        {
            if (ActivityConfig.IsTest)
                HttpContext.Current.Session[Keys.UserDatastr] = new UserData { WeixinUserId = 1 };
        }

        private void AuthWeixin(object sender)
        {
            bool isNeedAuth = HttpContext.Current.Handler is IAuthWeixin; //如果继承自IAuthWeixin则需要授权认证
            if (!isNeedAuth)
                return;

            Init(sender);
            InitTest();
            if (HasSession()) //这边对UserData的session赋值是在微信授权登录以后设置的
            {
                return;
            }
            if (string.IsNullOrEmpty(_request.QueryString["code"]))
            {
                string isbase = ConfigurationManager.AppSettings["Isbase"]; //这是判断是否使用简单授权登陆（不需要用户点击的那种）
                //todo 这里改成根据地址来判断
                ActivityConfig activityConfig = ActivityConfig.GetActivityConfig();
                string url = string.Format(_snsapi_userinfo, activityConfig.AppId, _request.Url);
                if (isbase != null && isbase == "true")
                    url = string.Format(_snsapi_baseUrl, activityConfig.AppId, _request.Url);

                _response.Redirect(url);
            }
            else
            {
                string code = _request.QueryString["code"];
                ActivityConfig activityConfig = ActivityConfig.GetActivityConfig();
                OAuthAccessTokenResult oAuthAccessToken = CommonApi.GetOAuthToken(activityConfig.AppId,
                    activityConfig.AppSecrect, code);

                bool flag = CommonApi.CheckAccessToken(oAuthAccessToken.access_token, oAuthAccessToken.openid);
                if (flag)
                {
                    OAuthWeixinUserInfoResult oAuthWeixinUser =
                        CommonApi.GetOAuthWeixinUserInfo(oAuthAccessToken.access_token,
                            oAuthAccessToken.openid);

                    WeixinUser weixinUser = RelayQuery.AddWeixinUser(oAuthWeixinUser);
                    AddSession(weixinUser);
                }
            }
        }

        /// <summary>
        ///     判断session中记录了授权登陆后的信息
        /// </summary>
        /// <returns></returns>
        private bool HasSession()
        {
            return SessionHelp.ValidUserData();
        }

        private void Init(object sender)
        {
            //必须只在这些属性被asp.net赋值后调用
            var app = (HttpApplication)sender;
            _context = app.Context;
            _request = _context.Request;
            _response = _context.Response;
            _session = app.Session;
        }

        private void AddSession(WeixinUser weixinUser)
        {
            var userData = new UserData
            {
                OpenId = weixinUser.OpenId,
                WeixinUserId = weixinUser.Id,
                HeadUrl = weixinUser.Headimgurl
            };
            SessionHelp.UserData = userData;
        }

        #region field

        private HttpContext _context;
        private HttpRequest _request;
        private HttpResponse _response;
        private HttpSessionState _session;

        private string _snsapi_baseUrl =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

        private string _snsapi_userinfo =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

        #endregion
    }
}